package ua.kharkov.knure.pereverziev.diploma.web;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import ua.kharkov.knure.pereverziev.diploma.web.command.Command;
import ua.kharkov.knure.pereverziev.diploma.web.command.CommandsContainer;

/**
 * Main servlet controller.
 * 
 * @author A.Pereverziev
 * 
 */
@SuppressWarnings("serial")
public class AjaxController extends HttpServlet {

	private static final Logger log = Logger.getLogger(AjaxController.class);

	CommandsContainer commands = CommandsContainer.getInstance();

	@Override
	protected void doGet(final HttpServletRequest request,
			final HttpServletResponse response) throws ServletException,
			IOException {
		process(request, response);
	}

	@Override
	protected void doPost(final HttpServletRequest request,
			final HttpServletResponse response) throws ServletException,
			IOException {
		process(request, response);
	}

	/**
	 * Main method of this controller.
	 */
	private void process(final HttpServletRequest request,
			final HttpServletResponse response) throws IOException,
			ServletException {
		log.debug("Controller starts");

		// extract command name from the request
		final String commandName = request.getParameter("command");
		log.debug("Request parameter: command --> " + commandName);

		// obtain command object by its name
		final Command command = commands.get(commandName);
		log.debug("Obtained command --> " + command.toString());

		final PrintWriter writer = response.getWriter();

		writer.println(command.execute(request, response));
		writer.flush();
		writer.close();
		log.debug("Controller finished");
	}

	public CommandsContainer getCommands() {
		return commands;
	}

	public void setCommands(final CommandsContainer commands) {
		this.commands = commands;
	}

}
